//
//  DetailViewController.m
//  Mango
//
//  Created by lanou3g on 16/5/6.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

//详情网址
#define DetailURL @"http://api.app.happyjuzi.com/article/detail"
//友盟APPKEY
#define UMAPPK @"5732892867e58e1088001f00"

#import "DetailViewController.h"
#import "DetailModel.h"
#import "HeaderView.h"
#import "FooterCollectionView.h"
#import <SVProgressHUD.h>
#import "UMSocial.h"
#import "DBManager.h"
#import "XJUserInfoManager.h"
#import "LoginViewController.h"
@interface DetailViewController () <UIWebViewDelegate,FooterCollectionViewDelegate>
@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) NSMutableString *content;
@property (strong, nonatomic) NSMutableArray *imgArray;
@property (nonatomic, strong) DetailModel *model;
//头部标题视图
@property (nonatomic, strong) HeaderView *headerView;

//尾部视图
@property (nonatomic, strong) FooterCollectionView *footerView;
//渲染html的view
@property (nonatomic, strong) UIView *webBrowserView;
@property (nonatomic, weak) UIView *shadeView;//(页面模式时，用来使页面变暗)
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor whiteColor];
    self.imgArray = [NSMutableArray array];
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenSizeW, ScreenSizeH)];
    self.webView.delegate = self;
    
    [self.view addSubview:self.webView];

    self.headerView = [HeaderView headerView];
    [self.webView.scrollView addSubview:self.headerView];
    self.webBrowserView = self.webView.scrollView.subviews[0];
    
    self.footerView = [[FooterCollectionView alloc]initWithFrame:CGRectZero];
    self.footerView.delegate = self;
    [self.webView.scrollView addSubview:self.footerView];
    
    [self loadDataFromServer];
    
    //监听webView的大小
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:nil];
    
    NSString *collectBtnTitle = nil;
    if ([[DBManager shareManager]hasCollect:self.ID]) {
        collectBtnTitle = @"取消收藏";
    }else {
        collectBtnTitle = @"收藏";
    }
    
    UIBarButtonItem *shareBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
    UIBarButtonItem *collectBtn = [[UIBarButtonItem alloc]initWithTitle:collectBtnTitle style:(UIBarButtonItemStylePlain) target:self action:@selector(collectBtnAction:)];
    self.navigationItem.rightBarButtonItems = @[collectBtn,shareBtn];
    [self setupShadeView];//换肤
}

-(void)viewWillAppear:(BOOL)animated {    //换肤
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
}

-(void)viewWillDisappear:(BOOL)animated {   //换肤
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--初始化shadeView(页面模式时，用来使页面变暗)
- (void)setupShadeView {      //换肤
    UIView *shadeView = [[UIView alloc] init];
    shadeView.backgroundColor = [UIColor blackColor];
    shadeView.alpha = 0.3;
    shadeView.userInteractionEnabled = NO;
    shadeView.frame = self.webView.bounds;
    self.shadeView = shadeView;
    [self.webView addSubview:shadeView];
}


#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
- (void)updateSkinModel {
    NSString  *currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.view.backgroundColor = [UIColor blackColor];
        self.webBrowserView.backgroundColor = [UIColor colorWithRed:34/255.0 green:30/255.0 blue:33/255.0 alpha:1.0];
        self.navigationController.navigationBar.tintColor = [UIColor grayColor];
        self.headerView.backgroundColor = [UIColor colorWithRed:34/255.0 green:30/255.0 blue:33/255.0 alpha:1.0];
        [self.headerView updateToNightSkinMode];
        [self.footerView updateToNightSkinMode];
        
        self.shadeView.hidden = NO;
    } else {//日间模式
        self.view.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.webBrowserView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.headerView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.shadeView.hidden = YES;
    }
}

//分享按钮点击事件
- (void)shareAction {
    //构造分享内容
    NSString *imgUrlStr = [self.model.img componentsSeparatedByString:@"!"][0];
    
    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:imgUrlStr];
    [UMSocialData defaultData].extConfig.title = self.model.title;
    [UMSocialData defaultData].shareText = [NSString stringWithFormat:@"%@+%@",self.model.title,self.model.shareurl];
    [UMSocialData defaultData].shareImage = imgUrlStr;
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:@"sina"];
    snsPlatform.snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    
}

//收藏按钮点击事件
- (void)collectBtnAction:(UIBarButtonItem *)sender {
    if (![XJUserInfoManager shareManager].loginStatus) {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:nil];
    }
    if ([sender.title isEqualToString:@"收藏"]) {
        [sender setTitle:@"取消收藏"];
        [[DBManager shareManager]collectLeftModel:self.listmodel];
    }else {
        [sender setTitle:@"收藏"];
        [[DBManager shareManager]cancelCollectArticle:self.ID];
    }
}


- (void)loadDataFromServer {
    NSDictionary *parDict = @{@"id":@(self.ID),@"net":@"wifi",@"pf":@"ios",@"res":@"320x568",@"uid":@"3971854834692451",@"ver":@"2.11"};
    
   [[AFHTTPSessionManager manager]GET:DetailURL parameters:parDict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = responseObject[@"data"];
        DetailModel *model = [[DetailModel alloc]init];
        [model setValuesForKeysWithDictionary:dataDict];
        self.model = model;
        
        [self.webView loadHTMLString:model.contents baseURL:nil];
        self.headerView.model = model;
        self.webBrowserView.y = [HeaderView heightForHeaderView];
        self.headerView.frame = CGRectMake(0, 0, ScreenSizeW, [HeaderView heightForHeaderView]);
        
        self.footerView.dataSource = model.recommend.mutableCopy;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth=375;" //缩放系数
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height * (maxwidth/oldwidth);"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    UIScrollView *webScroll = (UIScrollView *)object;
    self.footerView.frame = CGRectMake(0, webScroll.contentSize.height, ScreenSizeW , 460);
    self.webView.scrollView.contentSize = CGSizeMake(0, webScroll.contentSize.height + 460);
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:nil];
}

#pragma mark - FooterCollectionViewDelegate
- (void)footerCollectionView:(UICollectionView *)collectionView didClickItemAtIndexPath:(NSIndexPath *)indexPath {
    recommendModel *model = self.model.recommend[indexPath.row];
    DetailViewController *detailVC = [[DetailViewController alloc]init];
    detailVC.ID = model.ID;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)dealloc {
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
}

@end
